<template lang="pug">
div(v-if='media')
  div(style='margin-bottom: 32px')
    router-link(to='edit')
      h2 {{ media.title }} - 单元管理
  div(style='margin-bottom: 16px')
    //- router-link(to='unit/add') 新增单元
    Button(type='primary', icon='plus' @click='$router.push("unit/add")') 新增单元
  table.table
    thead
      tr
        td #
        td(style='width: 200px') 标题
        td 媒体链接
        td(style='width: 40px') 类型
        td(style='width: 120px') 操作
    tbody
      tr(v-for='(unit, index) in units')
        td {{ index + 1 }}
        td {{ unit.title }}
        td(style='word-break: break-all')
          a(:href='unit.abs_url', target='_blank') {{ unit.media_url.split('/').pop() }}
        td {{ unit.type }}
        td
          Button(size='small', type='primary', icon='edit', @click='edit(index)') 编辑
          | &nbsp;&nbsp;
          Button(size='small', type='error', icon='ios-trash', @click='remove(index)') 删除
</template>

<script>
import mediaApi from '@/apis/media'
import OSS from '@/libs/oss'

export default {
  beforeRouteEnter (to, from, next) {
    mediaApi.getMediaDetail(to.params.id).then(data => {
      OSS.getClient().then(({client}) => {
        next(vm => {
          vm.client = client
          vm.media = data
        })
      })
      // next(vm => (vm.media = data))
    })
  },
  data () {
    return {
      // client: null,
      media: null
    }
  },
  computed: {
    units () {
      return this.media && this.media.units.map(unit => {
        if (unit.media_url.indexOf('oss://') === 0) {
          unit.abs_url = this.client.signatureUrl(unit.media_url.replace('oss://', ''))
        } else {
          unit.abs_url = unit.media_url
        }

        return {
          ...unit,
          type: /\.mp3$/.test(unit.media_url) ? '音频' : '视频'
        }
      })
    }
  },
  methods: {
    edit (idx) {
      // let unit = this.media.units[idx]
      // unit.title = 'aaa'
      this.$router.push({
        name: 'edit-media-unit',
        params: { id: this.$route.params.id, delta: idx }
      })
    },
    remove (idx) {
      this.$Modal.confirm({
        title: '删除此单元?',
        content: this.units[idx].title,
        loading: true,
        onOk: () => {
          // console.log(idx)
          mediaApi.deleteMediaUnit({
            id: this.$route.params.id,
            delta: idx
          }).then(() => {
            this.media.units.splice(idx, 1)
            this.$Modal.remove()
          })
        }
      })
    }
  }
}
</script>
